<template>
  <div class="score-stats-container">
    <!-- 查询表单 -->
    <el-form :inline="true" :model="queryParams" class="header">
      <el-form-item label="班级">
        <el-select
          v-model="queryParams.classId"
          placeholder="请选择班级"
          clearable
          filterable
          remote
          :remote-method="remoteClassSearch"
          :loading="classLoading"
          @change="handleClassChange"
        >
          <el-option
            v-for="classItem in classList"
            :key="classItem.classId"
            :label="classItem.className"
            :value="classItem.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="课程名">
        <el-input
          v-model="queryParams.courseName"
          placeholder="请输入课程名"
          clearable
        />
      </el-form-item>
      <el-form-item label="学期">
        <el-select
          v-model="queryParams.semesterId"
          placeholder="请选择学期"
          clearable
          @change="handleSemesterChange"
        >
          <el-option
            v-for="semester in semesterList"
            :key="semester.id"
            :label="semester.year + '学年第' + semester.term + '学期'"
            :value="semester.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getClassCourseStatsData"
          >查询</el-button
        >
        <el-button type="warning" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 课程成绩统计卡片 -->
    <div v-if="courseStats.length > 0" class="stats-cards">
      <el-row :gutter="20">
        <el-col :span="12" v-for="(course, index) in courseStats" :key="index">
          <el-card class="stats-card" shadow="hover">
            <div slot="header" class="card-header">
              <span>
                {{ course.courseName }} ({{ course.className }})
                <template
                  v-if="
                    course.semesterId ||
                    course.semesterYear ||
                    queryParams.semesterId
                  "
                >
                  <el-tag size="small" type="success" class="semester-tag">
                    {{ getSemesterDisplay(course) }}
                  </el-tag>
                </template>
              </span>
            </div>
            <div class="card-content">
              <div class="stats-info">
                <div class="stat-item">
                  <span class="label">平均分</span>
                  <span class="value">{{ course.avgScore.toFixed(2) }}</span>
                </div>
                <div class="stat-item">
                  <span class="label">最高分</span>
                  <span class="value">{{ course.maxScore }}</span>
                </div>
                <div class="stat-item">
                  <span class="label">最低分</span>
                  <span class="value">{{ course.minScore }}</span>
                </div>
                <div class="stat-item">
                  <span class="label">及格率</span>
                  <span class="value"
                    >{{ (course.passRate * 100).toFixed(2)
                    }}<span class="unit">%</span></span
                  >
                </div>
                <div class="stat-item">
                  <span class="label">优秀率</span>
                  <span class="value"
                    >{{ (course.excellentRate * 100).toFixed(2)
                    }}<span class="unit">%</span></span
                  >
                </div>
                <div class="stat-item">
                  <span class="label">良好率</span>
                  <span class="value"
                    >{{ (course.goodRate * 100).toFixed(2)
                    }}<span class="unit">%</span></span
                  >
                </div>
                <div class="stat-item">
                  <span class="label">总人数</span>
                  <span class="value">{{ course.totalStudents }}</span>
                </div>
              </div>

              <div class="chart-container">
                <el-tabs v-model="course.activeChart">
                  <el-tab-pane label="饼图" name="pie">
                    <v-chart
                      v-if="course.activeChart === 'pie'"
                      class="chart"
                      :option="getScoreDistributionPieOption(course, false)"
                      autoresize
                    />
                  </el-tab-pane>
                  <el-tab-pane label="柱状图" name="bar">
                    <v-chart
                      v-if="course.activeChart === 'bar'"
                      class="chart"
                      :option="getScoreDistributionBarOption(course, false)"
                      autoresize
                    />
                  </el-tab-pane>
                </el-tabs>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 无数据提示 -->
    <div
      v-if="courseStats.length === 0"
      style="text-align: center; color: #999; padding: 40px 0"
    >
      暂无数据
    </div>
  </div>
</template>

<script>
import { getClassCourseStats } from "@/api/score";
import { getAllSemester } from "@/api/semester";
import { getAllClassInfo, getClassByCurrentUser } from "@/api/class";
import { mapState } from "vuex";

export default {
  name: "ScoreStats",
  computed: {
    ...mapState("user", ["userInfo"]),
  },
  data() {
    return {
      queryParams: {
        classId: null,
        className: "",
        courseName: "",
        semesterId: null,
      },
      courseStats: [],
      semesterList: [],
      classList: [],
      classLoading: false,
      // 分数区间定义
      scoreRanges: [
        { min: 0, max: 59, label: "不及格(0-59)" },
        { min: 60, max: 69, label: "及格(60-69)" },
        { min: 70, max: 79, label: "良好(70-79)" },
        { min: 80, max: 89, label: "优良(80-89)" },
        { min: 90, max: 100, label: "优秀(90-100)" },
      ],
    };
  },
  methods: {
    resetQuery() {
      this.queryParams = {
        classId: "",
        className: "",
        courseName: "",
        semesterId: null,
      };
      this.getClassCourseStatsData();
      this.getClassList();
    },

    /**
     * 计算当前学期对象
     * @param {Array} semesters 学期列表
     * @param {String} currentDateStr 可选，指定日期
     * @returns {Object|null} 当前学期对象或最近的学期
     */
    getCurrentTerm(semesters, currentDateStr) {
      const currentDate = new Date(currentDateStr || new Date());
      const sortedSemesters = semesters
        .map((s) => ({
          ...s,
          startDateObj: new Date(s.startDate),
          endDateObj: new Date(s.endDate),
        }))
        .sort((a, b) => a.startDateObj - b.startDateObj);
      for (let sem of sortedSemesters) {
        if (currentDate >= sem.startDateObj && currentDate <= sem.endDateObj) {
          return sem;
        }
      }
      let previousSemester = null;
      for (let sem of sortedSemesters) {
        if (currentDate >= sem.endDateObj) {
          previousSemester = sem;
        } else {
          break;
        }
      }
      return previousSemester;
    },

    async getSemesterList() {
      const res = await getAllSemester();
      if (res.code === 200) {
        this.semesterList = res.data;
        // 自动选中当前学期
        if (!this.queryParams.semesterId && this.semesterList.length > 0) {
          const currentSemester = this.getCurrentTerm(this.semesterList);
          if (currentSemester) {
            this.queryParams.semesterId = currentSemester.id;
          }
        }
        // 学期赋值后再请求数据
        this.getClassCourseStatsData();
      }
    },

    async getClassList() {
      this.classLoading = true;
      try {
        // 使用新的接口获取当前用户可访问的班级
        const res = await getClassByCurrentUser();
        if (res.code === 200) {
          this.classList = res.data;

          // 如果当前用户选择了班级，但该班级不在返回的列表中（说明无权限）
          if (this.queryParams.classId) {
            const hasPermission = this.classList.some(
              (c) => c.id === this.queryParams.classId
            );
            if (!hasPermission) {
              this.$message.warning("您只能查询自己教授的班级");
              this.queryParams.classId = null;
              this.queryParams.className = "";
            }
          }
        }
      } catch (error) {
        console.error("获取班级列表失败", error);
      } finally {
        this.classLoading = false;
      }
    },

    async remoteClassSearch(query) {
      this.classLoading = true;
      try {
        // 使用新的接口进行班级搜索
        const res = await getClassByCurrentUser(query);
        if (res.code === 200) {
          this.classList = res.data;
        }
      } catch (error) {
        // 可以根据需要做错误提示
      } finally {
        this.classLoading = false;
      }
    },

    handleClassChange(classId) {
      if (classId) {
        const selectedClass = this.classList.find((c) => c.id === classId);
        if (selectedClass) {
          this.queryParams.className = selectedClass.className;
        }
      } else {
        this.queryParams.className = "";
      }
      this.getClassCourseStatsData();
    },

    handleSemesterChange() {
      this.getClassCourseStatsData();
    },

    async getClassCourseStatsData() {
      try {
        // 调用真实API
        const res = await getClassCourseStats(this.queryParams);

        if (res.code === 200) {
          this.courseStats = res.data;

          // 处理数据，为每个课程计算不同分数段的人数
          this.courseStats.forEach((course) => {
            // 确保每个课程都有学期ID，如果后端没有返回，则使用当前查询的学期ID
            // 注意：后端应该在getClassCourseStats查询中添加 s.semester_id AS semesterId 字段
            if (!course.semesterId && this.queryParams.semesterId) {
              course.semesterId = this.queryParams.semesterId;
            }

            // 如果后端没有返回分布数据，则在前端计算
            if (!course.scoreDistribution) {
              // 如果API返回了原始成绩数据
              if (course.scores && course.scores.length > 0) {
                course.scoreDistribution = this.calculateScoreDistribution(
                  course.scores
                );
              } else {
                // 如果API没有返回原始成绩，使用默认空分布
                course.scoreDistribution = this.scoreRanges.map((range) => ({
                  range: range.label,
                  count: 0,
                }));
              }
            }
            // 初始化默认激活的图表类型
            course.activeChart = course.activeChart || "pie";
          });
        } else {
          this.$message.error(res.msg || "获取数据失败");
        }
      } catch (error) {
        this.$message.error("获取数据失败");
      }
    },

    // 计算分数分布
    calculateScoreDistribution(scores) {
      const distribution = this.scoreRanges.map((range) => ({
        range: range.label,
        count: 0,
      }));

      scores.forEach((score) => {
        for (let i = 0; i < this.scoreRanges.length; i++) {
          const range = this.scoreRanges[i];
          if (score >= range.min && score <= range.max) {
            distribution[i].count++;
            break;
          }
        }
      });

      return distribution;
    },

    // 生成成绩分布饼图配置
    getScoreDistributionPieOption(course, showTitle = true) {
      // 如果API已经返回了分布数据，使用API的数据
      const distribution = course.scoreDistribution || [];

      const ranges = distribution.map((item) => item.range);
      const counts = distribution.map((item) => item.count);

      // 计算各区间百分比
      const total = counts.reduce((sum, count) => sum + count, 0);
      const percentages = counts.map((count) =>
        ((count / total) * 100).toFixed(1)
      );

      // 为不同分数段设置不同颜色
      const colors = ["#F56C6C", "#E6A23C", "#409EFF", "#67C23A", "#909399"];

      // 获取学期名称 - 优先使用课程自带的学期信息
      let semesterName = "";
      if (course.semesterYear && course.semesterTerm) {
        // 如果后端直接返回了学期年份和学期
        semesterName = `${course.semesterYear}学年第${course.semesterTerm}学期`;
      } else if (course.semesterId) {
        // 如果只返回了学期ID，则从学期列表中查找
        const semester = this.semesterList.find(
          (s) => s.id === course.semesterId
        );
        if (semester) {
          semesterName = `${semester.year}学年第${semester.term}学期`;
        }
      } else if (this.queryParams.semesterId) {
        // 如果课程没有学期信息，则使用查询参数的学期
        const semester = this.semesterList.find(
          (s) => s.id === this.queryParams.semesterId
        );
        if (semester) {
          semesterName = `${semester.year}学年第${semester.term}学期`;
        }
      }

      // 构建图表标题，包含课程名和学期
      const titleText = semesterName
        ? `${course.courseName} (${semesterName})`
        : course.courseName;

      return {
        title: showTitle
          ? {
              text: titleText,
              left: "center",
            }
          : undefined,
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b}: {c}人 ({d}%)",
        },
        legend: {
          orient: "vertical",
          left: 10,
          data: ranges,
        },
        series: [
          {
            name: "成绩分布",
            type: "pie",
            radius: ["30%", "70%"],
            avoidLabelOverlap: false,
            label: {
              show: true,
              formatter: "{b}: {c}人 ({d}%)",
            },
            emphasis: {
              label: {
                show: true,
                fontSize: "18",
                fontWeight: "bold",
              },
            },
            labelLine: {
              show: true,
            },
            data: ranges.map((range, index) => ({
              value: counts[index],
              name: range,
              itemStyle: {
                color: colors[index],
              },
            })),
          },
        ],
      };
    },

    // 生成成绩分布柱状图配置
    getScoreDistributionBarOption(course, showTitle = true) {
      // 如果API已经返回了分布数据，使用API的数据
      const distribution = course.scoreDistribution || [];

      const ranges = distribution.map((item) => item.range);
      const counts = distribution.map((item) => item.count);

      // 为不同分数段设置不同颜色
      const colors = ["#F56C6C", "#E6A23C", "#409EFF", "#67C23A", "#909399"];

      // 获取学期名称 - 优先使用课程自带的学期信息
      let semesterName = "";
      if (course.semesterYear && course.semesterTerm) {
        // 如果后端直接返回了学期年份和学期
        semesterName = `${course.semesterYear}学年第${course.semesterTerm}学期`;
      } else if (course.semesterId) {
        // 如果只返回了学期ID，则从学期列表中查找
        const semester = this.semesterList.find(
          (s) => s.id === course.semesterId
        );
        if (semester) {
          semesterName = `${semester.year}学年第${semester.term}学期`;
        }
      } else if (this.queryParams.semesterId) {
        // 如果课程没有学期信息，则使用查询参数的学期
        const semester = this.semesterList.find(
          (s) => s.id === this.queryParams.semesterId
        );
        if (semester) {
          semesterName = `${semester.year}学年第${semester.term}学期`;
        }
      }

      // 构建图表标题，包含课程名和学期
      const titleText = semesterName
        ? `${course.courseName} (${semesterName})`
        : course.courseName;

      return {
        title: showTitle
          ? {
              text: titleText,
              left: "center",
            }
          : undefined,
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
          formatter: "{b}: {c}人",
        },
        xAxis: {
          type: "category",
          data: ranges,
          axisLabel: {
            interval: 0,
            rotate: 0,
            overflow: "break",
            lineHeight: 18,
          },
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: 60,
          containLabel: true,
        },
        yAxis: {
          type: "value",
          name: "人数",
          minInterval: 1, // 确保坐标轴刻度为整数
        },
        series: [
          {
            name: "人数",
            type: "bar",
            data: counts.map((count, index) => ({
              value: count,
              itemStyle: {
                color: colors[index],
              },
            })),
            label: {
              show: true,
              position: "top",
              formatter: "{c}人",
            },
          },
        ],
      };
    },

    getSemesterName(semesterId) {
      // 如果传入的是对象且包含年份和学期信息
      if (
        typeof semesterId === "object" &&
        semesterId.semesterYear &&
        semesterId.semesterTerm
      ) {
        return `${semesterId.semesterYear}学年第${semesterId.semesterTerm}学期`;
      }

      const semester = this.semesterList.find((s) => s.id === semesterId);
      if (semester) {
        return `${semester.year}学年第${semester.term}学期`;
      }
      return "";
    },

    // 获取课程的学期显示文本
    getSemesterDisplay(course) {
      // 优先使用课程自带的学期年份和学期信息
      if (course.semesterYear && course.semesterTerm) {
        return `${course.semesterYear}学年第${course.semesterTerm}学期`;
      }
      // 其次使用课程的学期ID
      else if (course.semesterId) {
        return this.getSemesterName(course.semesterId);
      }
      // 最后使用查询参数的学期ID
      else if (this.queryParams.semesterId) {
        return this.getSemesterName(this.queryParams.semesterId);
      }
      return "";
    },
  },
  mounted() {
    this.getSemesterList();
    this.getClassList();
  },
};
</script>

<style lang="scss" scoped>
.stats-card,
.card-content {
  min-height: 300px !important;
}
.chart-container,
.chart {
  min-height: 350px !important;
  height: 350px !important;
}
.score-stats-container {
  padding: 20px;

  .header {
    margin-bottom: 20px;
  }

  .stats-cards {
    margin-top: 20px;

    .stats-card {
      margin-bottom: 20px;

      .card-header {
        font-weight: bold;
        font-size: 16px;
        display: flex;
        align-items: center;
        justify-content: space-between;

        .semester-tag {
          margin-left: 8px;
          font-size: 12px;
        }
      }

      .card-content {
        display: flex;
        flex-direction: column;

        .stats-info {
          display: flex;
          flex-wrap: wrap;
          margin-bottom: 10px;
          justify-content: space-between;
          gap: 8px 0;

          .stat-item {
            width: 32%;
            background: #f7f9fa;
            border-radius: 8px;
            padding: 6px 0 2px 0;
            margin-bottom: 5px;
            text-align: center;
            box-shadow: 0 1px 4px rgba(0, 0, 0, 0.03);

            .label {
              display: block;
              font-size: 12px;
              color: #909399;
              margin-bottom: 2px;
              letter-spacing: 1px;
            }

            .value {
              display: block;
              font-size: 18px;
              font-weight: 600;
              color: #409eff;
              margin-left: 0;
              letter-spacing: 1px;
              .unit {
                font-size: 12px;
                color: #909399;
                margin-left: 2px;
              }
            }
          }
        }

        .chart-container {
          width: 100%;
          height: 350px;

          .chart {
            width: 100%;
            height: 100%;
          }
        }
      }
    }
  }
}
</style>
